<template>
  <el-dialog :title="titleMap[mode]" v-model="visible" append-to-body width="750" destroy-on-close :close-on-click-modal="false" @closed="$emit('closed')">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" :disabled="mode === 'show'" v-loading="loading">
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="form.templateName" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="通知方式">
        <el-checkbox-group v-model="form.templateMode">
          <el-checkbox v-for="dict in message_type" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="参数定义">
        <el-form :style="{ width: '100%' }" :model="fieldForm" :rules="fieldRule" ref="fieldForm" label-width="100px" :disabled="mode === 'show'">
          <el-row :gutter="15">
            <el-col :span="10">
              <el-form-item prop="field">
                <el-input v-model="fieldForm.field" placeholder="参数名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item prop="fieldName">
                <el-input v-model="fieldForm.fieldName"  placeholder="参数说明" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <el-button text type="primary" @click="addParameter">添加</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="tag__list">
          <el-tag v-for="(tag, index) in templateJson" :key="tag.field" effect="plain" :closable="tag.closable" @close="onTagClose(index)" @click="addContent(tag)" style="margin-right: 5px"> {{ tag.fieldName ? tag.field + "(" + tag.fieldName + ")" : tag.field }}</el-tag>
        </div>
      </el-form-item>
      <el-form-item label="通知内容" prop="messageContent">
        <el-input v-model="form.messageContent" type="textarea" placeholder="请输入内容" rows="5"/>
        <span style="color: red">* 参数请使用{param}</span>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"  rows="5"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  emits: ["success", "closed"],
  data() {
    return {
      mode: "add",
      titleMap: {
        add: "新增模板",
        edit: "编辑模板",
        show: "查看模板"
      },
      visible: false,
      isSaveing: false,
      loading: false,
      // 模板参数集合
      templateJson: [],
      // 表单参数
      form: {
        id: null,
        templateName: null,
        templateMode: [],
        parameter: null,
        messageContent: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null
      },
      // 表单校验
      rules: {
        templateName: [{ required: true, message: "模板名称不能为空", trigger: "blur" }],
        templateMode: [{ required: true, message: "通知方式不能为空", trigger: "blur" }],
        messageContent: [{ required: true, message: "通知内容不能为空", trigger: "blur" }]
      },
      // 自定义参数
      fieldForm: {
        field: "",
        fieldName: ""
      },
      // 自定义参数校验
      fieldRule: {
        field: [{ required: true, message: "参数名不能为空", trigger: "blur" }],
        fieldName: [{ required: true, message: "字段不能为空", trigger: "blur" }]
      },
      message_type: []
    }
  },
  mounted() {
    this.getDict()
  },
  methods: {
    //显示
    open(mode = "add") {
      this.mode = mode
      this.visible = true
      return this
    }, //表单提交方法
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.parameter = JSON.stringify(this.templateJson)
          const form = { ...this.form, ...{ templateMode: this.form.templateMode.join(",") } }
          if (this.form.id != null) {
            this.$API.system.template.updateTemplate.put(form).then(() => {
              this.$message.success("修改成功")
              this.$emit("success")
              this.visible = false
            })
          } else {
            this.$API.system.template.addTemplate.post(form).then(() => {
              this.$message.success("新增成功")
              this.$emit("success")
              this.visible = false
            })
          }
        }
      })
    },
    //表单注入数据
    async setData(data) {
      this.loading = true
      const res = await this.$API.system.template.getTemplate.get(data.id)
      this.templateJson = JSON.parse(res.data.parameter)
      Object.assign(this.form, res.data, { templateMode: res.data.templateMode.split(",") })
      this.loading = false
    },
    async getDict() {
		const res = await this.$API.system.msg.configs.get(null)
		if (res.code == 200){
			this.message_type = res.data;
		}
    },
    addParameter() {
      this.$refs["fieldForm"].validate((valid) => {
        if (valid) {
          let boo = this.templateJson.some((o) => o.field === this.fieldForm.field)
          if (boo) {
            this.$message({
              type: "error",
              message: "参数名重复，请重新输入"
            })
            return
          }
          this.templateJson.push({
            ...this.fieldForm,
            closable: true
          })
          this.$refs["fieldForm"].field = ''
        }
      })
    },
    // 关闭tag
    onTagClose(index) {
      this.templateJson.splice(index, 1)
    },
    // 添加参数内容
    addContent(item) {
      this.form.messageContent += "{" + item.field + "}"
    }
  }
}
</script>

<style lang="scss" scoped>
.tag__list {
  margin-top: 5px;
  ::v-deep .el-tag {
    cursor: pointer;
  }
}
</style>
